<?php

namespace app\common\model;

use think\Model;

class Orderjd extends Model
{
    // 表名
    protected $name = 'order_jd';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = false;

    // 定义时间戳字段名
    protected $createTime = false;
    protected $updateTime = false;
    
    // 追加属性
    protected $append = [
        'finishTime_text',
        'orderTime_text',
	    'valid_code_text',
	    'status_text'
    ];
	
	
	const STATUS_P = 0;
    const STATUS_W = 1;
    const STATUS_R = 2;
    const STATUS_Y = 3;
    const STATUS_C = 4;
	
    public static $statusList = [
    	self::STATUS_P => '待付款',
        self::STATUS_W => '待结算',
	    self::STATUS_R => '待返利',
	    self::STATUS_Y => '已返利',
	    self::STATUS_C => '订单关闭'
    ];
	
	public function getStatusTextAttr($value, $data) {
		$value = $value ? $value : $data['status'];
		$list = self::$statusList;
		return isset($list[$value]) ? $list[$value] : '';
	}


    const ORDER_STATUS_15 = 15;
	const ORDER_STATUS_16 = 16;
	const ORDER_STATUS_17 = 17;
	const ORDER_STATUS_18 = 18;
	
	public static $orderStatusList = [
		self::ORDER_STATUS_15 => '待付款',
		self::ORDER_STATUS_16 => '已付款',
		self::ORDER_STATUS_17 => '已完成',
		self::ORDER_STATUS_18 => '已结算',
	];
	
	public function getValidCodeTextAttr($value, $data) {
		$value = $value ? $value : $data['validCode'];
		$list = self::$orderStatusList;
		return isset($list[$value]) ? $list[$value] : '无效';
	}

    public function getFinishtimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['finishTime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getOrdertimeTextAttr($value, $data)
    {
        $value = $value ? $value : $data['orderTime'];
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setFinishtimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }

    protected function setOrdertimeAttr($value)
    {
        return $value && !is_numeric($value) ? strtotime($value) : $value;
    }
	
	/**
	 * 京东佣金返利
	 * @param $order 订单信息
	 * @param $config 返利配置
	 * @return bool
	 * @throws \think\exception\PDOException
	 */
	public function rebate($order, $config){
		$this->startTrans();
		try {
			//更改状态
			$orderRes = $this->save([
				'status' => self::STATUS_Y,
			], ['id' => $order['id']]);
			
			if(!$orderRes) {
				throw new Exception('更改订单状态出错');
			}
			
			//查找已经生成的待返利记录
			$rebateModel = new RebateRecord();
			$rebateRes = $rebateModel->rebate($order['orderId'], $rebateModel::TYPE_JD);
			if(!$rebateRes) {
				throw new Exception($rebateModel->getError());
			}
			
			
			$this->commit();
			return true;
			
		} catch (Exception $e) {
			$this->error = $e->getMessage();
			$this->rollback();
			return false;
		}
	}
}
